#include "CUnit.h"
#include "SGD Wrappers/CSGD_Direct3D.h"
#include "SGD Wrappers/CSGD_TextureManager.h"
#include "CObjectManager.h"
#include "SGD Wrappers/CSGD_DirectInput.h"
#include "CGamePlayState.h"
#include "CGame.h"
#include "SGD Wrappers/SGD_Math.h"

CUnit::CUnit()
{
	m_nType = UNIT;
	m_nUnitType = BASE_UNIT;
	m_pHero = NULL;
}
CUnit::~CUnit()
{

}
void CUnit::SetHero(CHero *pHero)
{
	if(m_pHero != NULL)
		m_pHero->Release();

	m_pHero = pHero;

	if(m_pHero)
		m_pHero->AddRef();
}
void CUnit::Init()
{

}
void CUnit::Update(float fDelta)
{
	float posX = GetPosX();
	float posY = GetPosY();
	
	tVector2D travelingVec;
	travelingVec.fX = 0;
	travelingVec.fY = -1;

	travelingVec.fX = (m_pHero->GetPosX() + m_pHero->GetWidth()/2) - posX;
	travelingVec.fY = (m_pHero->GetPosY() + m_pHero->GetHeight()/2) - posY;

	travelingVec = travelingVec * (fDelta/2);

	if(abs(Vector2DLength(travelingVec)) > 0.5)
	{
		SetVelX(travelingVec.fX);
		SetVelY(travelingVec.fY);
		SetPosX(posX + GetVelX());
		SetPosY(GetPosY() + GetVelY());
	}
	else if( abs(Vector2DLength(travelingVec)) < 0.5)
	{
		SetVelX(-travelingVec.fX);
		SetVelY(-travelingVec.fY);
		SetPosX(posX + GetVelX());
		SetPosY(posY + GetVelY());
	}
	else
	{
		SetPosX(posX);
		SetPosY(posY);
	}
}
void CUnit::Render()
{
	RECT temp;
	temp.top = (LONG)GetPosY();
	temp.bottom = (LONG)(GetPosY() + 10);
	temp.left = (LONG)GetPosX();
	temp.right = (LONG)(GetPosX() + 10);
	CSGD_Direct3D::GetInstance()->SpriteEnd();
	CSGD_Direct3D::GetInstance()->DrawRect(temp,0,255,0);
	CSGD_Direct3D::GetInstance()->SpriteBegin();
}
bool CUnit::Collision(CBase *pBase)
{
	RECT temp;
	RECT this1 = GetCollisionRect();
	RECT incoming = pBase->GetCollisionRect();

	if(IntersectRect(&temp, &this1, &incoming))
	{
		if(pBase->GetType() == UNIT)
		{
			return true;
		}
		else if(pBase->GetType() == HERO)
		{
			return true;
		}	
		else
			return false;
	}	
	else
		return false;
}
bool CUnit::CheckDistance(CBase *pBase, float fDelta)
{
	float myX = GetPosX() + GetWidth();
	float myY = GetPosY() + GetHeight();
	float NeighborX = pBase->GetPosX() + pBase->GetWidth()/2;
	float NeighborY = pBase->GetPosY() + pBase->GetHeight()/2;

	tVector2D tempVec;
	tempVec.fX = 0;
	tempVec.fY = -1;

	tempVec.fX = NeighborX - myX;
	tempVec.fY = NeighborY - myY;

	//tempVec = tempVec * fDelta;
	if(abs(Vector2DLength(tempVec)) > GetWidth() || abs(Vector2DLength(tempVec)) > GetHeight())
		return false;
	else
	{
		SetVelX(-tempVec.fX + rand()%((5+5)-5));
		SetVelY(-tempVec.fY);
		SetPosX(myX + GetVelX());
		SetPosY(myY + GetVelY());
		return true;
	}
		
}